package client;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;


public class PasswordHandler {
	
	/**
	 * A method that is hashing the password+salt a thousand times. 
	 * @param password The users password
	 * @param salt A variable salt
	 * @return a byte array with the generated hash. 
	 */
	public static byte[] hashPassword(String password, String salt){
		byte[] hash = null;
		byte[] salt1 = salt.getBytes();
		int iterations = 1000;
		try {
			MessageDigest md = MessageDigest.getInstance("SHA-1");
			md.reset();
			md.update(salt1);
			hash = md.digest(password.getBytes());
			for (int i = 0; i < iterations; i++){
				md.reset();
				hash = md.digest(hash);
			}	
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return hash;
	}
	
	/**
	 * Generates a variable salt from 8 random bytes which is converted to a String for storing 
	 * in database
	 * @return Returns a random salt.  
	 */
	public static String generateSalt(){
		SecureRandom random;
		byte[] salt = new byte[8];
		try {
			random = SecureRandom.getInstance("SHA1PRNG");
			random.nextBytes(salt);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return hexToString(salt);
	}
	
	/**
	 * Converts a byte array to a string
	 * @param b The byte array that is to be converted. 
	 * @return the converted byte array in String form. 
	 */
	public static String hexToString(byte[] b){
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < b.length; i++){
			sb.append(Integer.toHexString(b[i] & 0xFF));
		}
		return sb.toString();
	}

	
	/**
	 * Generates a hash from a password that is emerged with an variable 8 byte salt. 
	 * @param args
	 */
	public static void main (String [] args){
		String salt = PasswordHandler.generateSalt();
		String password = "password7";
		String hashedPw = PasswordHandler.hexToString(hashPassword(password, salt));
		System.out.println("Salt: " + " " +salt);
		System.out.println("Hashed pw:" + " " + hashedPw);
		
	}
}